-- ========================================================
-- @File	: common.lua
-- @Brief	: 常用函数封装
-- @Author	: Leo Zhao
-- @Date	: 2016-05-05
-- ========================================================

-- lua数据输出
function dump(v)
	if not __dump then
		function __dump(v, t, p)    
			local k = p or "";

			if type(v) ~= "table" then
				table.insert(t, k .. " : " .. tostring(v));
			else
				for key, value in pairs(v) do
					__dump(value, t, k .. "[" .. key .. "]");
				end
			end
		end
	end

	local t = {'======== Lib:Dump Content ========'};
	__dump(v, t);
	print(table.concat(t, "\n"));
end

-- 字串分割
function split(s, d)
	if not s or string.len(s) <= 0 then return {} end;

	local t = {};
	local p = "(.-)" .. d;
	local r = 0;

	while r <= string.len(s) do
		local start, last, part = string.find(s, p, r);
		if not start then
			table.insert(t, string.sub(s, r));
			r = string.len(s) + 1;
		else
			if #part > 0 then table.insert(t, part) end;
			r = last + 1;
		end
	end

	return t;
end

-- 解析URL参数
function urlparam(s)
	if string.len(s or '') <= 0 then return {} end;

	local t = {};
	local finder = split(s, '&');

	for _, p in ipairs(finder) do
		local _1, _2, k, v = string.find(p, "([%[%]%w_]+)=(.+)");
		if k and v then
			if string.sub(k, -2) == '[]' then
				k = string.sub(k, 1, -3);
				t[k] = t[k] or {};
				table.insert(t[k], v);
			else
				t[k] = v;
			end
		end
	end

	return t;
end

-- 判断文件是否存在
function file_exists(f)
	s = io.open(f, 'r');
	if not s then return false end;
	io.close(s);
	return true;
end

-- 模拟继承
function inherit(base)
	local t = { super = base }
	setmetatable(t, { __index = function(t, k) return t.super[k] end })
	return t;
end

-- 模拟生成UUID
function uuid()
	local seeds = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
	local temp = {};

	for i = 1, 32 do table.insert(temp, seeds[math.floor(random(1, 16))]) end;
	return table.concat(temp);
end

-- 序列化一个table，用于Session
function serialize(t)
	local tt = type(t);

	if tt == 'nil' then
		return 'nil';
	elseif tt == 'string' then
		return '"' .. t .. '"';
	elseif tt == 'table' then
		local tmp = {};
		for k, v in pairs(t) do
			local key = type(k) == 'number' and ('[' .. k .. ']') or k;
			table.insert(tmp, key .. '=' .. serialize(v));
		end
		return '{' .. table.concat(tmp, ',') .. '}';
	else
		return tostring(t);
	end	
end

-- 反序列化一个table
function deserialize(s)
	return load('return ' .. s)();
end

-- 取出一个vendor
function vendor(class)
	return require('core.vendor.' .. class);
end
